import {
  AfterContentInit,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  SimpleChanges,
  ViewChild
} from '@angular/core';
import {CommonModule} from "@angular/common";
import type {ImportDoneEvent, ImportXMLResult} from 'bpmn-js/lib/BaseViewer';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import {HttpClient} from "@angular/common/http";
import {from, map, Observable, Subscription, switchMap} from "rxjs";
import {NzButtonModule} from 'ng-zorro-antd/button';
import {BpmnModelerService} from '@site/app/service/bpmn-modeler.service';
import {BpmnToolbarComponent} from '@site/app/components/bpmn-toolbar/bpmn-toolbar.component';
import {BpmnPanelComponent} from "@site/app/components/bpmn-panel/bpmn-panel.component";
import { NzIconModule } from 'ng-zorro-antd/icon';

@Component({
  selector: 'dkb-bpmn-designer',
  standalone: true,
  imports: [
    CommonModule,

    NzButtonModule,
    NzIconModule,
    BpmnToolbarComponent,
    BpmnPanelComponent
  ],
  templateUrl: './bpmn-designer.component.html',
  styleUrl: './bpmn-designer.component.css'
})
export class BpmnDesignerComponent implements AfterContentInit, OnChanges, OnDestroy, OnInit {
  @ViewChild('diagramContainer', {static: true}) private el?: ElementRef;
  @Input() private url?: string;
  @Output() private importDone: EventEmitter<ImportDoneEvent> = new EventEmitter();
  private modeler: BpmnModeler;
  isCollapse = false;

  constructor(private http: HttpClient, private bpmnModelerService: BpmnModelerService) {
    this.modeler  = this.bpmnModelerService.getModeler();
  }

  ngAfterContentInit(): void {
    this.modeler.attachTo(this.el?.nativeElement);
  }

  ngOnInit(): void {
    /*if (this.url) {
      this.loadUrl(this.url);
    }*/

  }

  ngOnChanges(changes: SimpleChanges) {
    // re-import whenever the url changes
    if (changes['url']) {
      this.loadUrl(changes['url'].currentValue);
    }
  }

  ngOnDestroy(): void {
    //this.bpmnJS.destroy();
  }

  createNewDiagram(): void {
    this.bpmnModelerService.createNewDiagram().then(() => {
      console.log('new process')
    });
  }

  /**
   * Load diagram from URL and emit completion event
   */
  loadUrl(url: string): Subscription {

    return (
      this.http.get(url, {responseType: 'text'}).pipe(
        switchMap((xml: string) => this.importDiagram(xml)),
        map(result => result.warnings),
      ).subscribe({
        next: (warnings) => {
          this.importDone.emit({
            warnings
          });
        },
        error: (err) => {
          this.importDone.emit({
            warnings: [],
            error: err
          });
        }
      })
    );
  }

  doCollapse() {
    this.isCollapse = !this.isCollapse;
  }


  /**
   * Creates a Promise to import the given XML into the current
   * BpmnJS instance, then returns it as an Observable.
   *
   * @see https://github.com/bpmn-io/bpmn-js-callbacks-to-promises#importxml
   */
  private importDiagram(xml: string): Observable<ImportXMLResult> {
    return from(this.modeler.importXML(xml));
  }



}
